<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'

import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { onMounted, onUnmounted, nextTick } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { MsgType } from '@/enums'
import type { Message, TimeMessages } from '@/types/room'
import { ref } from 'vue'
import type { ConsultOrderItem } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { OrderType } from '@/enums'
import type { Image } from '@/types/consult'
import { showToast } from 'vant'
import { provide } from 'vue'

import dayjs from 'dayjs'

const consult = ref<ConsultOrderItem>()

onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
  console.log(res)
})

// 消息列表  [{},{},{},{}]
const list = ref<Message[]>([])

const store = useUserStore()
const route = useRoute()

let socket: Socket

// 组件销毁
onUnmounted(() => {
  // 关闭
  socket.close()
})
// 组件渲染完毕
onMounted(async () => {
  // 建立链接，创建 socket.io 实例
  // console.log(baseURL)
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect成功')
  })

  // 聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = []
    console.log(data)
    // "2023-10-08 09:44:59" [{msgType:x,msg:{content:"2023-10-08 09:44:59"},createTime:"2023-10-08 09:44:59"},id:xxx}
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: '12345'
      })
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    // 判断是否还有消息
    loading.value = false
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    nextTick(() => {
      if (initialMsg.value) {
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      }
    })
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('error', event)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
    list.value = []
  })
  // 接收消息 在onMounted注册
  socket.on('receiveChatMsg', async (event) => {
    console.log(event)
    list.value.push(event)
    // nextTick() 延迟到dom渲染完成后执行
    await nextTick()
    // 更新消息状态，跟新为已读
    socket.emit('updateMsgStatus', event.id)
    // 屏幕 滚动到最下方
    window.scrollTo(0, document.body.scrollHeight)
  })
})

const sendText = (text: string) => {
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    // 谁发的，
    from: store.user?.id,
    // 发给谁
    to: consult.value?.docInfo?.id,
    // 消息类型
    msgType: MsgType.MsgText,
    // 消息
    msg: { content: text }
  })
}

const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}

// 下拉刷新的loading
const loading = ref(false)

// 是否是第一次加载
const initialMsg = ref(true)

//记录每段消息的开始时间，作为下一次请求的开始时间
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

const onRefresh = () => {
  console.log('请求了')
  // 下来出发刷新
  //向socket服务端发送数据 参数：pageSize: number, lastTime: string, orderId: string
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
provide('consult', consult)

// 完成评价
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <!-- 头部 -->
    <cp-nav-bar title="问诊室" />
    <!-- <room-status></room-status> -->
    <!-- 状态 1.待接诊 2.咨询中（24倒计时）3.已完成 -->
    <room-status :status="consult?.status" :countdown="consult?.countdown" />

    <!-- 消息， -->
    <!-- <room-message :list="list"></room-message> -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <!-- <room-action></room-action> -->
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
